import pandas as pd
import matplotlib.pyplot as plt
import os

# Path to the folder containing CSV files
folder_path = 'C:/Users/Win/Desktop/codes/test_result/Cypress'

# Ensure the folder exists
if not os.path.exists(folder_path):
    raise Exception(f"Folder does not exist: {folder_path}")


# Function to plot a metric over time and save the image
def plot_metric(df, metric_name, ylabel, color, title, save_path):
    plt.figure(figsize=(10, 5))
    plt.plot(df['Elapsed Time (s)'], df[metric_name], label=metric_name, color=color, linewidth=2)
    plt.title(title)
    plt.xlabel('Elapsed Time (s)')
    plt.ylabel(ylabel)
    plt.xticks(rotation=45)
    plt.ylim(bottom=0)  # Ensure Y-axis starts at 0
    plt.xlim(left=0)  # Ensure X-axis starts at 0
    plt.grid()
    plt.legend()
    plt.tight_layout()
    plt.savefig(save_path)
    plt.close()


# Iterate through each CSV file in the folder
for file_name in os.listdir(folder_path):
    if file_name.endswith('.csv'):
        file_path = os.path.join(folder_path, file_name)

        # Read the CSV file
        df = pd.read_csv(file_path, sep="\t", encoding="utf-16")

        # Ensure 'Elapsed Time (s)' is treated as a numeric column
        df['Elapsed Time (s)'] = pd.to_numeric(df['Elapsed Time (s)'], errors='coerce')

        # Prepare output file names
        base_name = os.path.splitext(file_name)[0]
        cpu_plot_path = os.path.join(folder_path, f"{base_name}_cpu.png")
        mem_plot_path = os.path.join(folder_path, f"{base_name}_mem.png")
        thread_plot_path = os.path.join(folder_path, f"{base_name}_thread.png")

        # Plot and save each metric
        plot_metric(df, 'Total CPU Usage (%)', 'CPU Usage (%)', 'red', 'CPU Usage Over Time', cpu_plot_path)
        plot_metric(df, 'Total Memory Usage (MB)', 'Memory Usage (MB)', 'green', 'Memory Usage Over Time',
                    mem_plot_path)
        plot_metric(df, 'Total Thread Count', 'Thread Number', 'blue', 'Thread Number Over Time', thread_plot_path)

print("Plots have been saved successfully!")
